﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace DeepEarth.Toolkit.Common.Utilities
{
    public class TextBoxEnterKeyBehavior : Behavior<TextBox>
    {
        KeyEventHandler keyHandler;

        protected override void OnAttached()
        {
            base.OnAttached();

            keyHandler = KeyDownHandler;
            AssociatedObject.AddHandler(UIElement.KeyDownEvent, keyHandler, false);            
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.RemoveHandler(UIElement.KeyDownEvent, keyHandler);
        }

        void KeyDownHandler(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Enter:
                    var exp = AssociatedObject.GetBindingExpression(TextBox.TextProperty);

                    if (exp != null)
                    {
                        exp.UpdateSource();
                    }
                    e.Handled = true;
                    break;
            }
        }
    }
}       